package com.bdqn.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;

import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * AliyunOSS对象存储工具类
 *
 * @author LILIBO
 * @since 2021-06-24
 */
public class AliyunOSSUtil {

    // 外网访问域名
    private static final String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
    // Bucket名称
    private static final String BACKET = "lioil";
    // AccessKeyId
    private static final String ACCESSKEYID = "LTAI5tD84C2n7pAwfBhYLyWa";
    // AccessKeySecret
    private static final String ACCESSKEYSECRET = "JOidf0hQk5vKD6X98xRCpvsAWQEz3A";
    // 上传成功后返回的URL
    private static final String SUCCESSURL = "http://lioil.oss-cn-shenzhen.aliyuncs.com";
    // 时间格式化
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    // 获得OSS连接
    public static OSS getOSSClient() {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        // 判断Bucket是否存在，如果不存在就创建
        if (!ossClient.doesBucketExist(BACKET)) {
            CreateBucketRequest backetRequest = new CreateBucketRequest(null);
            backetRequest.setBucketName(BACKET);
            // 设置读写权限
            backetRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(backetRequest);
        }
        return ossClient;
    }

    // 关闭OSS连接
    public static void closeOSSClient(OSS ossClient) {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 文件上传
     *
     * @param part 需要上传的文件
     * @return 返回上传的图片在OSS中的图片地址
     */
    public static String uploadFile(Part part) throws IOException {
        // 获得OSS连接
        OSS ossClient = getOSSClient();
        // 获取请求的信息
        String name = part.getHeader("content-disposition");
        // 获取原文件的后缀
        String ext = name.substring(name.lastIndexOf("."), name.length() - 1);
        // 上传至OSS的哪个文件夹下，规则 ./20210309/xxx.jpg
        String date = sdf.format(new Date());
        // UUID生成新文件名
        String newFileName = UUID.randomUUID() + ext;
        // 创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(BACKET, date + "/" + newFileName, part.getInputStream());
        // 上传文件
        ossClient.putObject(putObjectRequest);
        // 关闭OSS连接
        closeOSSClient(ossClient);
        return SUCCESSURL + "/" + date + "/" + newFileName;
    }

}